#ifndef __NETWORK_GOBANG_H__
#define __NETWORK_GOBANG_H__

#include "NetworkPlayer.hpp"
#include "KeyHandle.hpp"
#include "Judge.hpp"
#include "WinLogo.hpp"

class NetworkGobang
{
public:
	NetworkGobang(const string& blackPlayerName, const string& whitePlayerName)
	{
		inputInfo();
		
		ChessBoard* chessBoard = ChessBoard::getChessBoard();
		chessBoard->show();
		keyHandle = new KeyHandle;

		if (chessColor == "white")
		{
			whitePlayer = new NetworkPlayer(
				whitePlayerName,
				"white",
				keyHandle,
				peerIP,
				peerPort,
				true
			);

			blackPlayer = new NetworkPlayer(
				blackPlayerName,
				"black",
				keyHandle,
				selfIP,
				selfPort
			);
		}
		else
		{
			blackPlayer = new NetworkPlayer(
				blackPlayerName,
				"black",
				keyHandle,
				peerIP,
				peerPort,
				true
			);

			whitePlayer = new NetworkPlayer(
				whitePlayerName,
				"white",
				keyHandle,
				selfIP,
				selfPort
			);
		}
	}

	~NetworkGobang()
	{
		delete whitePlayer;
		delete blackPlayer;
		delete keyHandle;
	}

	void inputInfo()
	{
		cout << "Input chess color: ";
		cin >> chessColor;
		cout << "Input self IP: ";
		cin >> selfIP;
		cout << "Input self Port: ";
		cin >> selfPort;
		cout << "Input peer IP: ";
		cin >> peerIP;
		cout << "Input peer Port: ";
		cin >> peerPort;
	}

	void run()
	{
		bool gameOver = false;

		NetworkPlayer* players[] = {whitePlayer, blackPlayer};

		while (!gameOver)
		{
			for (NetworkPlayer* player : players)
			{
				player->waitPlaceChess();
				bool win = judge.isWin(player);
				if (win)
				{
					gameOver = true;
					logo.showWinPlayer(player->getName(), player->getColor());
					break;
				}
			}
		}
	}
private:
	string chessColor;
	string selfIP;
	string selfPort;
	string peerIP;
	string peerPort;
	KeyHandle* keyHandle;
	Judge judge;
	WinLogo logo;
	NetworkPlayer* whitePlayer;
	NetworkPlayer* blackPlayer;
};

#endif // !__NETWORK_GOBANG_H__
